﻿using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TiffLibrary;
using TiffLibrary.PixelFormats;

namespace WholeSlideImageLibrary.Formats.GenericTiff
{
    internal class WholeSlideImagePixelBuffer<T> : ITiffPixelBuffer<TiffRgba32> where T : unmanaged
    {
        private readonly Memory<T> _memory;
        private readonly int _width;
        private readonly int _height;

        public WholeSlideImagePixelBuffer(Memory<T> memory, int width, int height)
        {
            if (Unsafe.SizeOf<T>() * memory.Length < 4 * width * height)
            {
                throw new ArgumentException("destination is too small.", nameof(memory));
            }
            _memory = memory;
            _width = width;
            _height = height;
        }

        public int Width => _width;

        public int Height => _height;

        public ReadOnlySpan<TiffRgba32> GetReadOnlySpan()
        {
            Span<byte> span = MemoryMarshal.AsBytes(_memory.Span);
            return MemoryMarshal.Cast<byte, TiffRgba32>(span.Slice(0, 4 * _width * _height));
        }

        public Span<TiffRgba32> GetSpan()
        {
            Span<byte> span = MemoryMarshal.AsBytes(_memory.Span);
            return MemoryMarshal.Cast<byte, TiffRgba32>(span.Slice(0, 4 * _width * _height));
        }
    }
}
